import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { UserChapterDto } from './dto/user-chapter.dto';

@Injectable()
export class userChapterService {
  constructor(private readonly prisma: PrismaService) {}

 async updateStudyTime(userId: string,chapterId: string) {
    const chapter = await this.prisma.course_chapter.findFirst({
      where: {
        id: chapterId
      }
    })
    if(!chapter){
     return ;
    }
    await this.prisma.user_course_chapter.upsert({
      where: {
        userId_chapterId: {
          userId: userId,
          chapterId: chapterId
        }
      },
      update: {
        lastAt: new Date()
      },
      create: {
        userId: userId,
        courseId: chapter.courseId,
        chapterId: chapterId,
        lastAt: new Date()
      }
    })
   await this.prisma.user_course.update({
      where: {
        userId_courseId: {
          userId: userId,
          courseId: chapter.courseId
        }
      },
      data: {
        lastAt: new Date(),
        lastChapterId: chapterId
      }
    })
    return ;
  }
  async submitUserCourseChapter(userId: string, data: UserChapterDto) {
    // 使用Prisma事务同时执行所有数据库操作
    return this.prisma.$transaction(async (tx) => {
      // 1. 一次性获取所有需要的数据
      const [userCourse, chapter, chapterCount, userChapterCount] = await Promise.all([
        // 检查用户课程
        tx.user_course.findFirst({
          where: { userId, courseId: data.courseId }
        }),
        // 检查章节是否存在
        tx.course_chapter.findUnique({
          where: { id: data.chapterId }
        }),
      
        // 获取章节总数
        tx.course_chapter.count({
          where: { courseId: data.courseId }
        }),
        // 获取用户已完成章节数
        tx.user_course_chapter.count({
          where: { userId, courseId: data.courseId }
        })
      ]);

      // 2. 验证数据
      if (!userCourse) {
        throw new NotFoundException('用户没有该课程');
      }

      if (!chapter) {
        throw new NotFoundException(`章节不存在: ${data.chapterId}`);
      }

      // 3. 更新或创建用户章节数据
      const chapterData = {
        studyCount: data.studyCount,
        studyTime: data.studyTime,
        wrongCount: data.wrongCount,
        studyEnd: 1,//学习完标识
        lastAt: new Date()
      };


      await this.prisma.user_course_chapter.upsert({
        where: { 
          userId_chapterId: {
            userId,
            chapterId: data.chapterId
          }
        },
        update: chapterData,
        create: {
          ...chapterData,
          userId,
          courseId: data.courseId,
          chapterId: data.chapterId,
        }
      })

      const newUserChapterCount =   userChapterCount + 1;
      const chapterRatio = Math.round(100 * newUserChapterCount / chapterCount);

      await tx.user_course.update({
        where: { id: userCourse.id },
        data: {
          schedule: {
            chapterNum: chapterCount,
            chapterEnd: userChapterCount,
            chapterRatio
          },
          studyTime: { increment: data.studyTime },
          lastChapterId: data.chapterId
        }
      });

      return {
        statusCode: 200,
        message: '学习记录已保存!',
        data: {
          progress: {
            total: chapterCount,
            completed: newUserChapterCount,
            ratio: chapterRatio
          }
        }
      };
    });
  }
}
